var DATA_URL	= null;
var CONFIG_URL 	= location.pathname + 'application.xml'; 
var UPLOAD_URL  = null;
var PIC_ROOT 	= 'http://www.101stratford.com';

// create a quick treeview
var treeon 	= Event.create ('treeon');
var footon 	= Event.create ('footon');
var main 	= Event.create ('main');
var page 	= Event.create ('page');
var tree 	= Tree ('dtree');
tree.onselect = function (key) { Controller.getfolder (key); }
tree.onchange = function (key, state) { if (state) Controller.getnode (key, key); else treebar.invoke(); }
tree.transformer = function () { return hyperlink(this.name, '#folder/' + this.key.replace (/\//g,'--')); };


// views to draw the user interfaces
var toolbar = View.create ('addressbar', 'daddress', function ()
{
	var bit, off, hue, vue, optionson, optionbit, thumbbit, treebit, textbit, htm=[], file = Controller.selectedfile;
	viewbit		= Controller.getbit(Controller.bits.VIEWAS); 
	optionbit	= Controller.getbit(Controller.bits.OPTIONS); 
	thumbbit	= Controller.getbit(Controller.bits.THUMBNAILS); 
	treebit		= Controller.getbit(Controller.bits.TREEVIEW); 
	textbit		= Controller.getbit(Controller.bits.ADDRESSBAR);
	newbit		= Controller.getbit(Controller.bits.CREATENEW); 
	 
	// if (Toolbar)
//	 {
//    var tb=Toolbar(PIC_ROOT, 'Controller.resizer.invoke()');
//    tb.store ('back', '/webservices/images/explorer/restore_icon.gif');
//    tb.store ('save', '/webservices/images/explorer/i.p.save.gif');
//    tb.store ('remove', '/webservices/images/delete.gif');
//    tb.store ('new', '/webservices/images/explorer/new.gif');
//    tb.store ('view', '/webservices/images/xui.view.gif');
//    tb.store ('filter', '/webservices/images/explorer/smKeyWord.gif'); 
//	 }
	
	var seperator = '&nbsp;<font color=blue>&#149;</font>&nbsp;';
	
	htm.push ('<table cellpadding="0" cellspacing="0"><tr>');  
	htm.push ('<td nowrap>') 
	
	if (Controller.selectedfile)
	{
		htm.push ( '&nbsp;' + imagelink (PIC_ROOT+'/webservices/images/explorer/restore_icon.gif', 'main.invoke()', 'back') ); 
		htm.push ( '&nbsp;' + imagelink (PIC_ROOT+'/webservices/images/explorer/i.p.save.gif', 'Controller.save()', 'save') ); 
		htm.push ( '&nbsp;' + imagelink (PIC_ROOT+'/webservices/images/delete.gif', 'Controller.deletefile()', 'delete') + '&nbsp;'); 
	}
	else
	{
		vue=Controller.hasbit( Controller.bits.CREATENEW )?'&#171;':'&#187;' 
		htm.push ( '&nbsp;' + imagelink (PIC_ROOT+'/webservices/images/explorer/new.gif', 'Controller.setvalue("viewas", '+newbit+', toolbar)','new'+vue ));
		if (Controller.hasbit( Controller.bits.CREATENEW ))
		{  
			htm.push ('&nbsp;'+textlink ('file', 'Controller.createfile()', 'font-size:8pt'));  
			htm.push ('&nbsp;'+textlink ('folder', 'Controller.createfolder()', 'font-size:8pt'));  
		}
		htm.push (seperator);
		vue=Controller.hasbit( Controller.bits.VIEWAS )?'&#171;':'&#187;'
		htm.push ( '' + imagelink (PIC_ROOT+'/webservices/images/xui.view.gif', 'Controller.setvalue("viewas", '+viewbit+', toolbar)', 'view as'+vue) );
		if (Controller.hasbit( Controller.bits.VIEWAS ))
		{ 
			css=Controller.hasbit( Controller.bits.THUMBNAILS )?'text-decoration:line-through;':'';
			htm.push ('&nbsp;&nbsp;'+textlink ('thumbnails', 'Controller.setbit(Controller.bits.THUMBNAILS, true)', css+'font-size:8pt')); 
			if (Controller.hasbit( Controller.bits.THUMBNAILS ))
			{
				css=Controller.hasbit( Controller.bits.THUMBLARGE )?'text-decoration:line-through;':'';
				htm.push ('&nbsp;&nbsp;'+textlink ('large', 'Controller.setbit(Controller.bits.THUMBLARGE, true)', css+'font-size:8pt')); 
				css=!Controller.hasbit( Controller.bits.THUMBLARGE )?'text-decoration:line-through;':'';
				htm.push ('&nbsp;&nbsp;'+textlink ('small', 'Controller.setbit(Controller.bits.THUMBLARGE, false)', css+'font-size:8pt')); 
			}
			css=!Controller.hasbit( Controller.bits.THUMBNAILS )?'text-decoration:line-through;':'';
			htm.push ('&nbsp;&nbsp;'+textlink ('details', 'Controller.setbit(Controller.bits.THUMBNAILS, false)', css+'font-size:8pt')); 
		}
		
		htm.push (seperator);
		vue=Controller.hasbit( Controller.bits.OPTIONS )?'&#171;':'&#187;'
		htm.push ( '' + imagelink (PIC_ROOT+'/webservices/images/explorer/smKeyWord.gif', 'Controller.setvalue("viewas", '+optionbit+', toolbar)', 'filter by'+vue+'&nbsp;') );
		if (Controller.hasbit( Controller.bits.OPTIONS ))
		{ 
			for (var x=0;x<Controller.filetypes.length;x++)
			{
				bit=Math.pow(2,x);	 
				off=Controller.total & bit ? Controller.total - bit : Controller.total + bit;
				css=Controller.total & bit ? 'color:blue;' : 'text-decoration:line-through;';
				htm.push (''+imagelink (Controller.filetypes[x].icon, 'Controller.setvalue("total", '+off+')', Controller.filetypes[x].name+'s', css+'font-size:8pt'));
			} 
		}
		htm.push ( '&nbsp;&nbsp;' );
	} 
	
	htm.push ('<td nowrap>'); 
	htm.push ('<div id="tbo" style="width:455px;overflow:hidden;border:solid 1px;border-color:gray white white gray;padding-left:4px;background-color:#f0f0f0">')
	htm.push ('<table cellspacing=0 cellpadding=0><tr><td>')
	htm.push ('<img onload="Controller.resizer.invoke()" align="absmiddle" src="'+PIC_ROOT+'/webservices/images/explorer/fclose.gif"/>')
	htm.push ('&nbsp;</td><td nowrap>')
	if (Controller.hasbit( Controller.bits.ADDRESSBAR ))
	{
		htm.push ('<input id=abspath style="width:400px;border:none;font-size:9pt;"')
		htm.push (' value="' + Controller.abspath + '')
		if (file) htm.push ('/' + file.name + '');
		htm.push ('">')
	}
	else
	{
		htm.push ('<div id="tbi" style="width:400px;overflow:hidden;background-color:#f0f0f0">')
		htm.push (tree.getpath())
		if (file) htm.push (' &#187; <a style="font-size:9pt">' + file.name + '</a>');
		htm.push ('</div>')
	}
	htm.push ('</td>')
	htm.push ('<td align="center">')
	htm.push (imagelink (PIC_ROOT+'/webservices/images/geo_ad_'+(Controller.hasbit( Controller.bits.ADDRESSBAR )?'up':'dwn')+'_widg2.gif', 'Controller.setvalue("viewas", '+textbit+', toolbar)')) 
	htm.push ('</td>')
	htm.push ('<td align="center">')
	if (Controller.hasbit( Controller.bits.ADDRESSBAR )) htm.push (imagelink (PIC_ROOT+'/webservices/images/explorer/ico_arrow.gif', 'Controller.getfolder(abspath.value)')) 
	else htm.push (imagelink (PIC_ROOT+'/webservices/images/Refresh.bmp', 'Controller.getfolder(Controller.abspath)')) 
	htm.push ('</td>')
	htm.push ('</tr></table>')
	htm.push ('</div>')
	htm.push ('</td>'); 
	
	htm.push ('</td></tr></table>')
	return htm.join ('');
},null,attachworkspace);

var treebar = View.create ('treebar', 'dtree', function ()
{ 
	if (Controller.hasbit( Controller.bits.TREEVIEW )) return '<div id="dxtree" style="overflow:auto;background-color:#f0f0f0">' + tree.draw (true) + '</div>';
	else return '';
}, null, attachworkspace);

var navbar = View.create ('navbar', 'dnavbar', function ()
{
	var file = Controller.selectedfile, files = Controller.documents, htm=[];
	var name = file ? file.name : '';
	var path = file ? file.path : '';
	//if (!file) return '';
	htm.push ('<table cellpadding="4" cellspacing="0"><tr>');
	for (var x in files)
	{
		htm.push ('<td  '+(files[x].path==path?'style="background:url('+PIC_ROOT+'/webservices/images/bg.gif);border:solid 1px;border-color:white gray white white"':'')+'>');
		if (path==files[x].path) htm.push (files[x].name);
		else htm.push (textlink (files[x].name, 'Controller.openfile("'+files[x].path+'")'));
		htm.push (imagelink (PIC_ROOT+'/webservices/images/geo_ad_close_widg2.gif', 'Controller.removefile("'+files[x].path+'")'));
		htm.push ('</td>');
	}
	htm.push ('</tr></table>');
	return htm.join ('');
}); 
 
var toggler = View.create ('toggler', 'dsplitter', function ()
{ 
	var treebit = Controller.getbit( Controller.bits.TREEVIEW ); 
	return '<img onload="Controller.resizer.invoke()" onclick=\'Controller.setvalue("viewas", '+treebit+')\' src="'+PIC_ROOT+'/webservices/images/close_' + 
				(Controller.hasbit( Controller.bits.TREEVIEW ) ? 'off' : 'on')+ '.gif"/>';  
},null,attachworkspace );
 
var vtoggler = View.create ('vtoggler', 'dvsplitter', function ()
{ 
	var treebit = Controller.getbit( Controller.bits.FOOTIEW ); 
	return '<img onload="Controller.resizer.invoke()" onclick=\'Controller.setvalue("viewas", '+treebit+')\' src="'+PIC_ROOT+'/images/toggle.gif"/>';  
},null,attachworkspace );



var footbar = View.create ('addressbar', 'dfooter', function ()
{  
	var slidebit 	= Controller.getbit( Controller.bits.SLIDESHOW );
	var fullbit 	= Controller.getbit( Controller.bits.FULLSIZE );
	var uploadbit 	= Controller.getbit( Controller.bits.UPLOAD );
	var file = Controller.selectedfile, htm=[];
	htm.push ('<table>');
	if (Controller.selectedfile)
	{
		var lst=Controller.sorted[Controller.selected.type],drp='<select onchange="Controller.getfile(Controller.selected.type, this.value)">';
		for (var x=0;x<lst.length;x++)
		{
				drp+= '<option '+(Controller.selected.index==x?'selected':'')+' value="'+x+'">'+(x+1)+'</option>';
		}
		drp += '</select>';
		htm.push ('<tr>');
		htm.push ('<td valign=top><img src="' + file['large'] + '"></td>');
		htm.push ('<td valign=top width="200">');
		htm.push ('<font size=3 color="#000066">' + file['name'] + '</font>');
		htm.push ('<div class=small>' + file['type'] + '<br></div>');
		htm.push ('</td>');
		htm.push ('<td valign=top align=right class=small>Date:<br>Size:</td>');
		htm.push ('<td valign=top class=small nowrap>' + file['date'] + '<br>' + file['size'] + '</td>'); 
		htm.push ('<td valign=top class=small nowrap>&nbsp;&nbsp;&nbsp;' + 
				  			drp + ' of ' + 
							Controller.sorted[Controller.selected.type].length + ' ' + 
							Controller.selected.type + 's' + 
							'&nbsp;&nbsp;&nbsp;'); 
		htm.push (textlink ('&#171; back','Controller.advance(-1)') + '&nbsp;');
		htm.push (textlink ('next &#187;','Controller.advance(1)') + '&nbsp;&nbsp;&nbsp;');
		if (Controller.selectedfile.editor=='image')
		{
			htm.push (textlink ('slideshow','Controller.setvalue("viewas",'+slidebit+')', Controller.hasbit( Controller.bits.SLIDESHOW )  ? 'text-decoration:line-through' : ''));
			htm.push ('&nbsp;&nbsp;&nbsp;');
			if (!Controller.hasbit( Controller.bits.SLIDESHOW ))
			   htm.push (textlink ('actual size','Controller.setvalue("viewas",'+fullbit+')', Controller.hasbit( Controller.bits.FULLSIZE )  ? 'text-decoration:line-through' : ''));
		}
		htm.push ('</td></tr>');
	}
	else
	{
		htm.push ('<tr>');
		htm.push ('<td valign="top"><img onload="Controller.resizer.invoke()" src="' + PIC_ROOT + '/webservices/special/clean/x64/312x528.jpg.gif"></td>');
		htm.push ('<td valign="top">');
		htm.push ('<font size=3 color="#000066">' + Controller.abspath + '</font>');
		htm.push ('<div class=small>File Folder<br></div>');
		htm.push ('</td>'); 
		htm.push ('<td valign="bottom" nowrap>&nbsp;&nbsp;&nbsp;');  
		htm.push (textlink ('upload a file to '+Controller.abspath+'' + (Controller.hasbit( Controller.bits.UPLOAD )?'&#171;':'&#187;'),'Controller.setvalue("viewas",'+uploadbit+',footbar)','font-size:8pt' ));
		htm.push ('</td>'); 
		htm.push ('<td valign="bottom">');  
		if ( Controller.hasbit( Controller.bits.UPLOAD ) )
		{
			if (UPLOAD_URL)
			{
				htm.push ('&nbsp;&nbsp;&nbsp;Upload file: <input name=fileUpload type=file><input type=image src="'+PIC_ROOT+'/webservices/images/07.bmp">'); 
				htm.push ('<INPUT type="hidden" name=uploadTarget value="'+Controller.abspath+'">'); 
			}
			else
			{
				htm.push ('&nbsp;&nbsp;&nbsp;<font color="red">Sorry, file uploads not supported in this version</files>');
			}
		}
		htm.push ('</td>'); 
		htm.push ('</tr>');
	}
	htm.push ('<table>'); 
	return htm.join ('');
});

var fileview = View.create ('listview', 'dbody', function ()
{
	var size = GetFrameDimensions( document.getElementById('dbody') );
	var url  = 'http://www.101stratford.com/webservices/mvc/connector.php?action=getfileb&path=/webservices/mvc/connector.php?action=getfileb&path=';
	var file = Controller.selectedfile, htm=[]; 
	var tmr = 'processimage("'+file['path']+'")';
  
   
   
	var language='generic',languages = {	 
		css        : /.*\.(css)$/i,  
		html       : /.*\.(htm|html)$/i, 
		javascript : /.*\.(js)$/i, 
		php        : /.*\.(php)$/i, 
		text       : /.*\.(txt)$/i 
	}
    for (var x in languages)
	    if (re=languages[x].exec (file['path']))
		    language=x;

   
	if (file['editor']=='mp3')
	{
		var path='http://www.google.com/reader/ui/3247397568-audio-player.swf?audioUrl=' + escape ('http://' + location.hostname + file['path']);
		htm.push ('<br><embed ');
		htm.push ('classname="audio-player-embed" width="400px" height="27px" ');
		htm.push ('src="' + path + '"></embed><br>' + path) 
	}
	else if (file['editor']=='embed') htm.push ('<embed src="' + file['path'] + '" id="tcontent" name="tcontent"></embed>'); 
	else if (file['editor']=='iframe') htm.push ('<iframe src="' + file['path'] + '" id="tcontent" name="tcontent"></iframe>'); 
	//else if (file['content']) htm.push ('<iframe onload="attachworkspace (1)" id="tcontent" style="wordwrap:normal;" name="tcontent" src="' + url + file['path'] + '"></iframe>'); 
	else if (file['content']) htm.push ('<textarea style="width:'+size.x+';height:'+size.y+';" class="codepress ' + language + '" id="tcontent" wrap="off">' + Decoder.decode(file['content']) + '</textarea>'); 
	else htm.push ('<table id="tcontent"><tr><td align=center><img id="i' + file['path'] + '" onload=\''+tmr+'\' src="' + PIC_ROOT + '/webservices/images/Spinning_wheel_throbber.gif"></td></tr></table>');
 
	return htm.join ('');
}, null, function ()
{
	// CodePress.run();
	attachworkspace();
	var dw=document.getElementById ('tcontent');
	if (dw) 
	{
		var o;if (o=Controller.selectedfile)
		{
			if (Controller.scrolltop[o.name]) dw.scrollTop=Controller.scrolltop[o.name];
			dw.onscroll=function () { Controller.scrolltop[o.name]=this.scrollTop; }
		}
	}
});

var Decoder = {
	decode : function (x)
	{
		var o=Base64.decode(x);
		o=o.replace (/\&/g,'&amp;');
		o=o.replace (/>/g,'&gt;');
		o=o.replace (/</g,'&lt;');
		return o;
	}
}

function processimage(x)
{
	var id='i'+x,pic=document.getElementById (id); 
	var callback = Controller.hasbit( Controller.bits.SLIDESHOW ) ? 
									 function () { window.setTimeout ("Controller.advance(1)", 5000); } : 
									 attachworkspace;
	if (Controller.hasbit( Controller.bits.FULLSIZE ))
	{
		pic.onload=null;
		pic.src = x;
		callback();
		return true;
	}
	preLoadImage (x, id, dbody.offsetHeight - 20, callback);
}

var workspace = View.create ('listview', 'dbody', function ()
{
	var col=0,row=0,icon, href,htm =[];
	//var fclose = '<img width=16 src="' + PIC_ROOT + '/webservices/images/explorer/fclose.gif" align="absmiddle">'; 
 	
	if (Controller.count==0)
	{
		return 'The folder is empty';
	}
	
	htm.push ('<table width="100%" cellpadding=1 cellspacing=0>');
	
//	Controller.sortfiles ();
	var text, root='#folder/' +  Controller.abspath.replace (/\//g,'--');
	var limit = Controller.hasbit( Controller.bits.THUMBNAILS ) ? 8 : 75;
	if (Controller.hasbit( Controller.bits.THUMBNAILS ))
	{
		htm.push ('<tr>');
	}
	
	var size=Controller.getpicsize ();
	var span=Math.floor(dbody.offsetWidth / size)-2;
	for (var x=0;x<Controller.folders.length;x++)
	{  
		text = hyperlink(truncate(Controller.folders[x]['name'],limit), '#folder/' +  Controller.folders[x]['path'].replace (/\//g,'--'));
		if (Controller.hasbit( Controller.bits.THUMBNAILS ))
		{
			icon = '<img src="' + PIC_ROOT + '/webservices/special/clean/x64/312x528.jpg.gif" align="absmiddle">';  
			htm.push ('<td align=center>');
			htm.push ('' + icon + '<br>' + text + '');
			htm.push ('</td>');
			col++;
			if (col%span==0) htm.push ('</tr><tr>');
		}
		else
		{
			htm.push ('<tr>');
			htm.push ('<td nowrap="nowrap" colspan="4">' + fclose + '&nbsp;' + text); 
			htm.push ('</td><td width="100%"></td>'); 
			htm.push ('</tr>');
		}
	}
	
	var span=Math.floor(dbody.offsetWidth / size)-2;
	var filetype = '',hasbit=Controller.hasbit( Controller.bits.THUMBNAILS );
	for (var i in Controller.sorted)
	{  
		var icon,files = Controller.sorted[i]; 
		if (files.length>0)
		{ 
			var index=Math.pow(2, files[0]['index']);
			if (Controller.total & index)
			{
				if (!hasbit && filetype != i)
				{
					htm.push ('<tr>'); 
					htm.push ('<td nowrap="nowrap" colspan="5" class="tabon"><img src="'+files[0]['icon']+'" align="absmiddle"/> <b>' + i + 's</b></td>'); 
					htm.push ('</tr>');
				} 
				filetype = i; 
				
				for (var x=0;x<files.length;x++)
				{ 
					if (hasbit)
					{ 
						htm.push ( files[x].thumbitem (root, i, x, limit, size) ); 
						col++;
						if (col%span==0) htm.push ('</tr><tr>');
					}
					else
					{
						htm.push ( files[x].lineitem (root, i, x, limit) ); 
					}
				}
			}
		}
	}
	
	
	if (Controller.hasbit( Controller.bits.THUMBNAILS ))
	{
		htm.push ('</tr>');
	}
	htm.push ('</table>');
	return htm.join('');  
}, function() {Controller.selectedfile=null;}, attachworkspace);
page.add (fileview,footbar,toolbar,treebar,toggler,vtoggler,navbar);
main.add (workspace,footbar,toolbar,treebar,toggler,vtoggler,navbar);
treeon.add (treebar,toggler);
footon.add (footbar,vtoggler);

// configure the controller...
var filetype=function (name, pattern, icon, large, editor)
{
	return {
		name 		: name,
		pattern 	: pattern,
		icon 		: PIC_ROOT + icon ,
		large 		: PIC_ROOT + large ,
		editor 		: editor,
		match 		: function (x) { return this.pattern.exec (x); } 
	}
}
 

Controller.filetypes = [
	filetype ('image',/.*\.(jpg|gif|png|bmp|tif|jpeg)$/i,"/webservices/images/image_ico.gif", '/webservices/special/clean/x64/1032x1488.jpg.gif', 'image'),
	filetype ('xml file',/.*\.(cb|xml|xsl|wsdl|disco)$/i,"/webservices/images/docIconSm_xml.gif", '/webservices/special/clean/x64/600x1968.jpg.gif', 'text') ,
	filetype ('text file',/.*\.(doc|txt|htaccess|log|ini)$/i,"/webservices/images/explorer/icon.gif", '/webservices/special/clean/x64/744x1648.jpg.gif', 'text'),
	filetype ('script',/.*\.(js|vbs)$/i,"/webservices/images/explorer/ico_jscript.gif", '/webservices/special/clean/x64/744x1808.jpg.gif', 'text'),
	filetype ('pdf',/.*\.(pdf)/i,"/webservices/images/icon_pdf.gif", '/webservices/special/clean/x64/312x1808.jpg.gif', 'iframe'),
	filetype ('webpage',/.*\.(asp|htm|php|pl|cfm|css|html)$/i,"/webservices/images/explorer/WEBDOC.ICO.gif", '/webservices/special/clean/x64/600x1328.jpg.gif', 'text'),
	filetype ('media file',/.*\.(mp3|mp4|mpg|pls|mov)$/i,"/webservices/images/explorer/ico_wmp_xp.gif", '/webservices/special/clean/x64/600x1648.jpg.gif', 'embed')/*,
	filetype ('mp3 file',/.*\.(mp3)/i,"/images/icon.wmp.gif", '/webservices/special/clean/x64/600x1648.jpg.gif', 'mp3')*/ 
];
for (var x in Controller.filetypes)Controller.filetypes[x]['index']=x;
Controller.total=127;

Controller.sortfiles = function ()
{ 
	this.sorted = {};
	for (var x in this.files)
	{
		for (var i in this.filetypes)
		{
			if (this.filetypes[i].match (this.files[x].name))
			{
				if (!this.sorted[this.filetypes[i].name]) this.sorted[ this.filetypes[i].name ]=[];
				this.files[x].icon 		= this.filetypes[i].icon;
				this.files[x].large		= this.filetypes[i].large;
				this.files[x].editor 	= this.filetypes[i].editor;
				this.files[x].index 	= this.filetypes[i].index;
				this.sorted[this.filetypes[i].name].push (this.files[x]);
			}
		}
	}
}

Controller.getfile = function (filetype, index)
{ 
	Controller.selected={ type : unescape (filetype), index : index };
	if (Controller.sorted[Controller.selected.type])
	{
		if (Controller.sorted[Controller.selected.type][index])
		{
			Controller.selectedfile = Controller.sorted[Controller.selected.type][index]; 
			if (Controller.selectedfile.editor=='text') Webservice.getfile ('path', Controller.selectedfile.path); 
			else page.invoke (); 
		} else alert (name + ' file ' + index + ' was not found.'); 
	} else alert ('No files of type ' + name + ' were found.');
}

Controller.createfile = function ()
{ 
	var name;
	if (name=prompt ('Enter a name for the new file', 'untitled.htm'))
	{
		Webservice.createfile ("path", this.abspath + '/' + name);
	}
	Controller.setbit (Controller.bits.CREATENEW, false);
}

Controller.createfolder = function ()
{ 
	var name;
	if (name=prompt ('Enter a name for the new folder', 'untitled folder'))
	{
		Webservice.createfolder ("path", this.abspath + '/' + name);
	}
	Controller.setbit (Controller.bits.CREATENEW, false);
}

Controller.deletefile = function ()
{ 
	var file=Controller.selectedfile;
	if (!file) return false;
	if (confirm ('Delete '+file['name']+'?'))
	{
		Webservice.deletefile ("path", file['path']);
	}
}

Controller.getfolder = function (path)
{ 
	dbody.innerHTML = 'loading "'+path+'"...';
	Controller.abspath = path;
	Webservice.getfolder ('path', Controller.abspath);
	tree.items [path].expand(); 
	toolbar.invoke ();
}

Controller.onfileloaded = function (data)
{ 
	Controller.selectedfile.content = data;
	Controller.addfile (Controller.selectedfile);
	page.invoke(); 
}

Controller.onfiledeleted = function (data)
{ 
	alert (data);
	Controller.getfolder (Controller.abspath);
}

Controller.onfilecreated = function (data)
{ 
	alert (data);
	Controller.getfolder (Controller.abspath);
}

Controller.onfolderloaded = function (data, id, state)
{  
	if (state==200)
	{
		var dom=XmlDocument.create();   
		if (dom.loadXML (data))  
		{ 
			document.title = Controller.abspath;
			SerializeDomtoFolder (dom); 
			main.invoke ();
		} else alert ('Could not load xml ' + dom.parseError.reason + '\nline ' + dom.parseError.line + '\npos ' + dom.parseError.linepos + '\n' + data)
	}
	else
	{
		alert ('The specified DATA_URL "'+DATA_URL+'" was not found. Please check the application.xml file.');
		main.invoke ();
	}
} 

Controller.save = function ()
{
	var data = SerializeForSaving ();  
	if (data) Webservice.post ( data, function (x) {alert(x.length>0?x:'Save action failed!'); if(x=Controller.selectedfile) Webservice.getfile('path',x.path); }  );
}

Controller.handleHref = function (url, id)
{ 
	Controller.parseUrl (url); 
	if (Controller.QueryString['type'])
	{
		var i = Controller.QueryString['type'];
		var x = Controller.QueryString['index']; 
		Controller.getfile (i, x); 
	} 
	else if (Controller.QueryString['folder'])
	{
		var path = Controller.QueryString['folder'].replace (/--/g, '/'); 
		tree.select (path);
	}
}

Controller.removefile = function (x)
{
	var o={};
	Controller.selectedfile=null;
	for (var e in Controller.documents)
	{
		if (Controller.documents[e].path!=x) o[Controller.documents[e].path]=Controller.documents[e];
	}
	Controller.documents = o;
	Controller.getfolder (Controller.abspath);
}
 
Controller.openfile = function (x)
{
	Controller.selectedfile= Controller.documents[x];
	page.invoke ();
}

Controller.getnode = function (path, attach)
{
	Webservice.getfolder ('path', path, function (data) 
	{ 
		var dom=XmlDocument.create();   
		if (dom.loadXML (data))  
		{   
			var folders = dom.getElementsByTagName ('folder');  
			tree.items[attach].clear(); 
			for (var x=0;x<folders.length;x++)
			{ 
				if (folders[x].getAttribute ('name')!='..')
				{
					tree.add (folders[x].getAttribute ('name'), folders[x].getAttribute ('path'), attach); 
					if ( folders[x].getAttribute ('count') > 0 )
					{
						tree.add ('loading...', folders[x].getAttribute ('path') + '/sub', folders[x].getAttribute ('path')); 
					}
				}
			}
			// tree.draw();
			treebar.invoke();
		} 
	})
}

Controller.advance = function (i)
{
	var lst=Controller.sorted[Controller.selected.type],x=parseInt(Controller.selected.index);
	x += parseInt(i);
	if (x>lst.length-1)x=0;
	if (x<0)x=lst.length-1;
	Controller.getfile(Controller.selected.type, x);
}


Controller.addfile 		= function (o) { this.documents[o.path]=o;};
Controller.scrolltop 	= {};
Controller.documents 	= {};
Controller.optionson 	= false;
Controller.abspath 		= '/';
Controller.folders 		= [];
Controller.resizer 		= new DHTMLEvent(); 
Controller.scroller		= new DHTMLEvent(); 

Controller.watch (location, 'href', Controller.handleHref); 


var bits=[
		  'VIEWAS','OPTIONS','THUMBNAILS','TREEVIEW',
		  'ADDRESSBAR','SLIDESHOW','FULLSIZE','FOOTIEW',
		  'UPLOAD','THUMBLARGE','CREATENEW'
		  ];
Controller.bits={};for (var x=0;x<bits.length;x++) Controller.bits[ bits[x] ] = Math.pow (2,x);
Controller.getbit=function(i){ return this.hasbit(i)  ? Controller.viewas - i  : Controller.viewas - (-i);};
Controller.setbit=function(i,on){ var o=this.hasbit(i); if (!(o&&on)) this.setvalue('viewas',this.getbit(i)); };
Controller.hasbit=function(i){ return Controller.viewas & i;};
Controller.viewas = Controller.bits.TREEVIEW + Controller.bits.FOOTIEW + Controller.bits.FULLSIZE;
Controller.thumbsize = { small : 64 , large : 96};
Controller.getpicsize = function () { return this.hasbit(Controller.bits.THUMBLARGE) ? Controller.thumbsize.large : Controller.thumbsize.small; };

// set up webservice functions... 
Webservice.add ('getfolder', Controller.onfolderloaded);
Webservice.add ('getfile', Controller.onfileloaded);
Webservice.add ('deletefile', Controller.onfiledeleted);
Webservice.add ('createfile', Controller.onfilecreated);
Webservice.add ('createfolder', Controller.onfilecreated);
Webservice.add ('renamefile', function (x) {alert (x)});

// add a few helper functions
function truncate (x,y) { return x.length > y ? (x.substr(0,y)+'...') : x; }

function SerializeDomtoFolder (dom)
{
	var folders = dom.getElementsByTagName ('folder');
	var files 	= dom.getElementsByTagName ('file');
	Controller.folders	= [];
	Controller.files	= [];
	Controller.sorted	= {};
	Controller.count	= 0;
	 
	for (var x=0;x<folders.length;x++)
	{ 
		Controller.count++;
		Controller.folders.push ({name : folders[x].getAttribute ('name'),
								  path : folders[x].getAttribute ('path') 
									}); 
	}
	
	var node, type, name, serialize=SerializeFileNode;
	for (var x=0;x<files.length;x++)
	{ 
		for (var i in Controller.filetypes)
		{
			type = Controller.filetypes[i];
			name = type.name;
			if (type.match (files[x].getAttribute ('name')))
			{
				if (!Controller.sorted[ name ]) Controller.sorted[ name ]=[];
				node = serialize(files[x], type); 
				Controller.sorted[ name ].push ( node );
				Controller.count++;
				break;
			}
		}
	}  
}

function SerializeFileNode (node, filetype)
{
	return {
		name 		: node.getAttribute ('name'),
		path 		: node.getAttribute ('path'),
		size 		: node.getAttribute ('size'),
		type 		: node.getAttribute ('type'),
		date 		: node.getAttribute ('date'),
		icon 		: filetype['icon'],
		large 		: filetype['large'],
		editor 		: filetype['editor'],
		index 		: filetype['index'],
		lineitem	: function (root, type, index, limit)
		{
			var href = root + '/type/' + type + '/index/' + index;
			var text = hyperlink(truncate(this['name'], limit), href);
			var htm=[], icon = '<img width=16 src="' + this['icon'] + '" align="absmiddle">';  
			htm.push ('<tr>');
			htm.push ('<td nowrap="nowrap">' + icon + '&nbsp;' + text + '&nbsp;</td>');
			htm.push ('<td nowrap="nowrap" align="right">&nbsp;' + this['size'] + ' bytes</td>');
			htm.push ('<td nowrap="nowrap">&nbsp;' + this['type'] + '</td>');
			htm.push ('<td nowrap="nowrap">&nbsp;' + this['date'] + '</td>');
			htm.push ('<td width="100%"></td>'); 
			htm.push ('</tr>');
			return htm.join ('');
		},
		thumbitem	: function (root, type, index, limit, size)
		{ 
			var href 	= root + '/type/' + type + '/index/' + index;
			var sz 		= Controller.getpicsize ();
			var text 	= hyperlink(truncate(this['name'], limit), href, 'font-size:8pt');
			var scr  	= this['editor']=='image' ? ('preLoadImage("' + this['path'] + '", "i' + this['path'] + '", '+sz+')') : '';
			var htm=[], icon = '<a href="' + href + '"><img onload=\'' + scr + '\' src="' + this['large'] + '" id="i' + this['path'] + '" align="absmiddle"></a>';  
			htm.push ('<td bgcolor="#F0F0F0" align=center nowrap valign=bottom>');
			htm.push ('<div style="width:' + size + 'px;height:' + (parseInt(size)+20) + 'px">');
			htm.push ('<table style="border:solid 1px #999" width=' + size + ' height=' + size + '><tr><td align=center>');
			htm.push ('' + icon + '');
			htm.push ('</td></tr></table>' + text + '</div></td>');
			return htm.join ('');
		}
	}
}
function ts() { var x=new Date();return x.getSeconds() + '.' + x.getMilliseconds(); };

function getIFrameDocument(aID){
  // if contentDocument exists, W3C compliant (Mozilla)
  if (document.getElementById(aID).contentDocument){
    return document.getElementById(aID).contentDocument;
  } else {
    // IE
    return document.frames[aID].document;
  }
}


function SerializeForSaving ()
{
	var dw=document.getElementById ('tcontent');
	if (dw)
	{
	  var mycontent=dw.value; 
 
		htm=[];
		htm.push ('<savefile datapath="' + Controller.selectedfile.path + '"><![CDATA[');
		htm.push (Base64.encode(mycontent));
		htm.push (']]></savefile>');
 
		return htm.join ('');
	}
	return '';
}

function GetFrameDimensions(object)
{
    var ho=Controller.hasbit(Controller.bits.FOOTIEW) ? 100 : 20;
    var pos = getPosition(object); 
	return {
		x:( window_w() - pos.x - 20 ) + 'px',
		y:( window_h() - pos.y - ho ) + 'px'
	}
}

window['AttachCodepress2Form'] = function (object)
{  
	var codepress = object;
	window['GetCodepressSource'] = function () 
	{
		return codepress.getCode ();
	};

	codepress.invoke = function ()
	{
	    var size = GetFrameDimensions(this);
		this.style.width 	= size.x; 
		this.style.height 	= size.y;
	}; 
		

	Controller.resizer.subscribe (codepress); 
	Controller.resizer.invoke ();
	
	codepress.onscroll = function ()
	{
			alert ('scroll!');
	}; 
		
     //alert ( codepress.tagName );
}




function attachworkspace ()
{ 
	var ho=Controller.hasbit(Controller.bits.FOOTIEW) ? 100 : 20;
	
	var dw=document.getElementById ('tcontent');
	if (dw)
	{  
		var framer = {
			invoke : function ()
			{
				var v=function (fr)
				{
					if (fr.length)
					{  
					//alert (fr.length);
						for (var x=0;x<fr.length;x++)
						{
							var that=fr[x],pos = getPosition(that); 
							that.style.width 	= ( window_w() - pos.x - 20 ) + 'px'; 
							that.style.height 	= ( window_h() - pos.y - ho ) + 'px';  
						}
					}
				}
				v (document.getElementsByTagName ('TEXTAREA'));
				// v (document.getElementsByTagName ('IFRAME'));
			}
		}
		
		Controller.resizer.subscribe (framer); 
		Controller.resizer.invoke ();
		
		
//        getIFrameDocument("tcontent").designMode = "On";
//		dw.invoke = function ()
//		{  
//			var pos = getPosition(this); 
//			this.style.width 	= ( window_w() - pos.x - 20 ) + 'px'; 
//			this.style.height 	= ( window_h() - pos.y - ho ) + 'px';   
//		}
//		Controller.resizer.subscribe (dw); 
//	    Controller.resizer.invoke ();
	} 
	
	var dw=document.getElementById ('tbo');
	if (dw)
	{
		dw.invoke = function ()
		{  
			var xo=['tbi','abspath'];
			var dw=document.getElementById ('tbi');
			var pos = getPosition(this);  
			this.style.width 	= ( window_w() - pos.x - 20 ) + 'px';  
			for (var x in xo) 
			{
				if (document.getElementById ( xo[x] ))
					document.getElementById ( xo[x] ).style.width = ( window_w() - pos.x - 75 ) + 'px';  
			}
		}
		Controller.resizer.subscribe (dw); 
	    Controller.resizer.invoke ();
	}
	var dw=document.getElementById ('dxtree');
	if (dw)
	{
		dw.invoke = function ()
		{  
			var pos = getPosition(this);  
			this.style.width 	= '200px';
			this.style.height 	= ( window_h() - pos.y - ho + 8 ) + 'px';    
		}
		Controller.resizer.subscribe (dw); 
	    Controller.resizer.invoke ();
	}
	
	var dw=document.getElementById ('dbody');
	if (dw)
	{
		dw.invoke = function ()
		{  
			var pos = getPosition(this); 
			if (Controller.selectedfile && Controller.hasbit( Controller.bits.FULLSIZE )) this.style.overflow = 'auto';
			else this.style.overflow = Controller.selectedfile ? 'hidden' : 'auto';
			this.style.width 	= ( window_w() - pos.x - 20 ) + 'px'; 
			this.style.height 	= ( window_h() - pos.y - ho ) + 'px';    
		}
		Controller.resizer.subscribe (dw); 
	    Controller.resizer.invoke ();
	}
}

function getPosition(e){
	var left = 0;
	var top  = 0;

	while (e.offsetParent){
		left += e.offsetLeft;
		top  += e.offsetTop;
		e     = e.offsetParent;
	}

	left += e.offsetLeft;
	top  += e.offsetTop;

	return {x:left, y:top};
}
function preLoadImage(path, id, sz, cb)
{
	var im 		= new Image();
	var size	= sz;
	var callbk	= cb;
	im.buddy 	= document.getElementById (id);
	im.onload 	= function ()
	{
		var point 			= imageresize (this.width, this.height, size);
		var caption 		= path+'\n'+this.width+'x'+this.height+' pixels';
		this.buddy.onload 	= null;
		this.onload 		= null;
		this.buddy.width 	= point.width;
		this.buddy.height 	= point.height;
		this.buddy.title 	= caption;
		this.buddy.src 		= this.src;
		if (callbk) callbk();
	}
	if (callbk)
	{
		im.buddy.invoke = function ()
		{
			if (Controller.hasbit( Controller.bits.FULLSIZE )) return false;
			var point 	= imageresize (this.width, this.height, dbody.offsetHeight - 20, true);
			this.width 	= point.width;  
			this.height = point.height; 
		}
		Controller.resizer.subscribe (im.buddy);
	}
	im.src = path;
}

function imageresize (w,h,s,v)
{
	var o={width: w, height : h}, ratio = w/h;
	if (w > s || h > s || v)
	{
		if (w>h)
		{
			o.width 	= s;
			o.height 	= s/ratio;
		}
		else
		{
			o.height 	= s;
			o.width 	= s*ratio;
		}
	}
	return o;
}

function onstart ()
{ 
	if (DATA_URL==CONFIG_URL || !DATA_URL)
	{
		alert ('No DATA_URL was specified. Please check the application.xml file.');
		return false;
	}
 	var homelabel='/';
	tree.add (location.hostname, homelabel);
    tree.add ('loading...', homelabel + '/sub', homelabel); 
	tree.items[homelabel].icon='<img src="' + PIC_ROOT + '/webservices/images/network.gif" align="absmiddle">';
	Controller.getfolder ('/'); 
}

function start ()
{ 
	DATA_URL = CONFIG_URL;
	Webservice.getfile ('path', '', function (data) 
	{ 
		var dom=XmlDocument.create();   
		if (dom.loadXML (data))  
		{   
			var name, value, add = dom.getElementsByTagName ('add');   
			for (var x=0;x<add.length;x++)
			{  
				name 	= add[x].getAttribute ('name');
				value 	= add[x].getAttribute ('value');
				if (name) window [name] = value;
			}  
			onstart ();
		} 
	});
}


function startCallback() 
{
	// make something useful before submit (onStart)
	//FolderList.uploader.invoke ();
//	alert (UPLOAD_URL);
	return true;
}

function completeCallback(response) 
{
	alert (response)
	Controller.getfolder (Controller.abspath)
}

function window_w() { return document.all ? document.body.offsetWidth : window.innerWidth;}
function window_h() { return document.all ? document.body.offsetHeight : window.innerHeight;}
window.onresize = function () { Controller.resizer.invoke (); }
main.afterinvoke = attachworkspace;
page.afterinvoke = attachworkspace;
var fclose 	= '<img width=16 onload="Controller.resizer.invoke()" src="'+PIC_ROOT+'/webservices/images/explorer/fclose.gif" align="absmiddle">';